﻿using System;
using System.Collections.Generic;
using Microsoft.Win32;

namespace unTroublemaker.Conditions
{
    public static class ServiceHelper
    {
        const int Automatic = 2;
        private static readonly Dictionary<int, string> StartupModes;

        static ServiceHelper()
        {
            StartupModes = new Dictionary<int, string> {{2, "Automatic"}, {3, "Manual"}, {4, "Disabled"}};
        }

        public static string GetStartupMode(string serviceName)
        {
            const String basepathStr = @"System\CurrentControlSet\services\";
            String subKeyStr = basepathStr + serviceName;

            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(subKeyStr, false))
            {
                if(key == null)
                    throw new Exception("Failed to locate service named: " + serviceName);

                var delayedAutoStartKey = key.GetValue("DelayedAutoStart");
                var delayed = delayedAutoStartKey != null && (int) delayedAutoStartKey == 1;

                var startupMode = (int)key.GetValue("Start");
                if (startupMode == Automatic)
                {
                    if (delayed)
                        return "Automatic (Delayed Start)";

                    return "Automatic";
                }
                
                return StartupModes[startupMode];
            }
        }
    }
}
